<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { TooltipEmits, TooltipProps } from './types';
import { createPopper, type Instance } from '@popperjs/core'

defineOptions({
  name: "Tooltip",
  trigger: 'hover',
});

const props = withDefaults(defineProps<TooltipProps>(),{
    placement: 'bottom',
}) 
const emits = defineEmits<TooltipEmits>()

const isOpen = ref(false)
const popperNode = ref<HTMLElement>()
const triggerNode = ref<HTMLElement>()
let popperInstance: null | Instance = null
let events: Record<string, any> = reactive({})
let outerEvents: Record<string, any> = reactive({})



const openFinal = () => {
  isOpen.value = true
  emits('visible-change', true)
}
const closeFinal = () => {
    isOpen.value = false
    emits('visible-change', false)
}

const popperOptions = computed(() => {
  return {
    placement: props.placement,
    modifiers: [
      {
        name: 'offset',
        options: {
          offset: [0, 9],
        },
      }
    ],
    ...props.popperOptions
  }
})

watch(isOpen, (newValue) => {
  if (newValue) {
    if (triggerNode.value && popperNode.value) {
      popperInstance = createPopper(triggerNode.value, popperNode.value, popperOptions.value)
    } else {
      popperInstance?.destroy()
    }
  }
}, { flush: 'post'})



const togglePopper = () => {
  isOpen.value =!isOpen.value
  emits('visible-change', isOpen.value)
}

const attachEvents = () => {
  if (props.trigger === 'hover') {
    events['mouseenter'] = openFinal
    outerEvents['mouseleave'] = closeFinal
  } else if (props.trigger === 'click') {
    events['click'] = togglePopper
  }
}

attachEvents()

watch(() => props.trigger, (newTrigger, oldTrigger) => {
  if (newTrigger !== oldTrigger) {
    events = {}
    outerEvents = {}
    attachEvents()
  }
})

</script>

<template>
  <div class="vk-tooltip"  ref="popperContainerNode"  v-on="outerEvents">
    <div class="vk-tooltip__trigger"  ref="triggerNode"  v-on="events">
      <slot />
    </div>
    <div class="vk-tooltip__popper"  ref="popperNode" v-if="isOpen">
      <slot name="content">  {{content}} </slot>
    </div>
  </div>
</template>

<style lang="scss" scoped></style>
